package media.opensync;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DirList extends Activity {

	public AdaptorFiles adaptor = new AdaptorFiles(this);
	private ListView listView;
	private String path;
	private TextView tv;
	private File f;
	public static final int SERVERPORT = 45658;
	public static String SERVERIP;
	public ServerSocket serverSocket ;
	private String fileName;
	public static SortedSet<String> filesToSend = new TreeSet<String>();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.files);
		SERVERIP = TheOpenSyncActivity.serverIp;
		path = TheOpenSyncActivity.path;
		tv = (TextView) findViewById(R.id.text);
		tv.setText(path);

		adaptor.addFiles(path);

		listView = (ListView)findViewById(R.id.list);
		listView.setAdapter(adaptor);
		Button back = (Button)findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String text = (String) tv.getText();
				int idx = text.lastIndexOf("/");
				path = text.substring(0, idx);
				if(path.equals("")) path = "/";
				tv.setText(path);
				TheOpenSyncActivity.path = path;
				adaptor.delList();
				adaptor.addFiles(path);
			}
		});
		Button menu = (Button)findViewById(R.id.menu);
		menu.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				openOptionsMenu();
			}
		});

		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
				TextView file = (TextView) adaptor.getItem(pos);
				if(TheOpenSyncActivity.path.endsWith("/")) TheOpenSyncActivity.path += file.getText();
				else TheOpenSyncActivity.path += "/" + file.getText();
				path = TheOpenSyncActivity.path;
				f = new File(path);
				if (f.isDirectory()) {
					tv = (TextView) findViewById(R.id.text);
					tv.setText(path);
					adaptor.delList();
					adaptor.addFiles(TheOpenSyncActivity.path);
				}
				else {
					fileName = (String) file.getText();
					markBox(fileName);
				}
			}
		});
	}

	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu,menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch (item.getItemId()){
		case R.id.menu1:
			this.finish();
			return true;
		case R.id.menu3:
			Intent myIntent = new Intent(DirList.this, TheOpenSyncActivity.class);
			DirList.this.finish();
			startActivity(myIntent);
			return true;
		case R.id.menu4:
			dialogBox();
			return true;
		case R.id.menu5:
			Intent intent = new Intent(DirList.this, ViewMarked.class);
			startActivity(intent);
			return true;
		}
		return false;
	}

	public void dialogBox(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to send the files?")
		.setCancelable(false)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				int nrFiles = filesToSend.size();
				
				try{
					Socket socket = new Socket(SERVERIP, SERVERPORT);
					
					DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
					//sending password:
					MDCalculator mdcalc = new MDCalculator(TheOpenSyncActivity.password);
					String pass = mdcalc.getMD();
					dos.writeUTF(pass);
					//sending number of files:
					dos.writeInt(nrFiles);
					
					Iterator<String> it = filesToSend.iterator();
					while(it.hasNext()){
						path = it.next();
						f = new File(path);
						int idx = path.lastIndexOf("/");
						int n = path.length();
						fileName = path.substring(idx + 1, n);
						sendFile(socket, dos);
					}
					filesToSend = new TreeSet<String>();
					dos.close();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show ();
	}
	
	public void markBox(String name){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Mark the file " + name + " to send?")
		.setCancelable(false)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				filesToSend.add(path);
				int idx = path.lastIndexOf("/");
	        	if (idx >= 0) path = path.substring(0, idx);
	        	if(path.equals("")) path = "/";
	        	TheOpenSyncActivity.path = path;
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				int idx = path.lastIndexOf("/");
				path = path.substring(0, idx);
				if(path.equals("")) path = "/";
				TheOpenSyncActivity.path = path;
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show ();
	}
	
	public void  sendFile(Socket socket, DataOutputStream dos) {
		
		try {			
			FileInputStream fis = new FileInputStream(f);
			int length = (int) f.length();
			byte [] byteArray = new byte[length];
			DataInputStream dis = new DataInputStream (new BufferedInputStream(fis));
			
			dis.readFully(byteArray);
			
			dos.writeInt(length);
			dos.writeUTF(fileName);		
			dos.write(byteArray);
			
			Toast.makeText(DirList.this, "Done", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			Toast.makeText(DirList.this, "ERRORrrrr! "+e.getMessage(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}
}
